package tree;

/**
 * Created with IntelliJ IDEA.
 * Description: 654. 最大二叉树
 * User: Li_yizYa
 * Date: 2025/6/5
 * Time: 20:36
 */
public class Solution25 {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        if (nums == null || nums.length == 0) {
            return null;
        }
        return traversal(nums, 0, nums.length - 1);
    }
    private TreeNode traversal(int[] nums, int left, int right) {
        if (left > right) {
            return null;
        }
        if (left == right) {
            return new TreeNode(nums[left]);
        }

        int maxIndex = left;
        for (int i = left; i <= right; i++) {
            if (nums[i] > nums[maxIndex]) {
                maxIndex = i;
            }
        }
        TreeNode root = new TreeNode(nums[maxIndex]);
        root.left = traversal(nums, left, maxIndex - 1);
        root.right = traversal(nums, maxIndex + 1, right);
        return root;
    }
}
